package com.example.administrator.testproject.download.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.example.administrator.testproject.R;


/**
 * Created by shengfh on 2017/12/18.
 */

public class RoundProgressBar extends View {

    public static class STATUS{
        public static final int START=0;//开始状态
        public static final int DOWN=1;//下载中
        public static final int PAUSE=2;//暂停
        public static final int FINISH=3;//完成
    }
    /**
     * 画笔对象的引用
     */
    private Paint paint;

    /**
     * 圆环的颜色
     */
    private int roundColor;

    /**
     * 圆环进度的颜色
     */
    private int roundProgressColor;

    /**
     * 中间进度百分比的字符串的颜色
     */
    private int textColor;
    /**
     * 中间进背景颜色
     */
    private int roundBackColor;

    /**
     * 中间进度百分比的字符串的字体
     */
    private float textSize;

    /**
     * 圆环的宽度
     */
    private float roundWidth;

    /**
     * 最大进度
     */
    private long max;

    /**
     * 当前进度
     */
    private long progress;
    /**
     * 是否显示中间的进度
     */
    private boolean textIsDisplayable;
    /**
     * 是否可以暂停，并且不显示进度值
     */
    private boolean isCheckPause;
    /**
     * 进度的风格，实心或者空心
     */
    private int style;

    private String textName;

    public static final int STROKE = 0;
    public static final int FILL = 1;
    private float lineWidth;
    private boolean isPause;
    private boolean isFirst=true;
    private OnCheckListener listener;
    private int status;
    private RectF oval=new RectF(4,4,116,116);
    int centre;
    int radius;
    public interface OnCheckListener{
        void onClickStatus(int status);
    }
    public void setOnPasueListener(OnCheckListener listener){
        this.listener=listener;
    }
    public RoundProgressBar(Context context) {
        this(context, null);
    }

    public RoundProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundProgressBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        paint = new Paint();
        lineWidth = 1;

        TypedArray mTypedArray = context.obtainStyledAttributes(attrs,
                R.styleable.RoundProgressBar);

        //获取自定义属性和默认值
        roundColor = mTypedArray.getColor(R.styleable.RoundProgressBar_roundColor,
                Color.BLUE);
        roundProgressColor = mTypedArray.getColor(R.styleable.RoundProgressBar_roundProgressColor,
                Color.BLUE);
        textColor = mTypedArray.getColor(R.styleable.RoundProgressBar_textColor,
                Color.BLUE);
        roundBackColor=mTypedArray.getColor(R.styleable.RoundProgressBar_roundBackColor,
                Color.TRANSPARENT);
        textSize = mTypedArray.getDimension(R.styleable.RoundProgressBar_textSize, 15);
        roundWidth = mTypedArray.getDimension(R.styleable.RoundProgressBar_roundWidth, 5);
        max = mTypedArray.getInteger(R.styleable.RoundProgressBar_max, 1000000000);
        textName = mTypedArray.getString(R.styleable.RoundProgressBar_title);
        textIsDisplayable = mTypedArray.getBoolean(R.styleable.RoundProgressBar_textIsDisplayable, true);
        isCheckPause = mTypedArray.getBoolean(R.styleable.RoundProgressBar_isCheckPause, false);
        style = mTypedArray.getInt(R.styleable.RoundProgressBar_style, 0);

        mTypedArray.recycle();

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("Tag","xxxxx");
                if (isCheckPause && listener!=null){
                    switch (status){
                        case STATUS.START:
                        case STATUS.PAUSE:
                            listener.onClickStatus(status);
                            break;
                        case STATUS.DOWN:
                            listener.onClickStatus(status);
                            status= STATUS.PAUSE;
                            postInvalidate();
                            break;
                    }
                }
            }
        });

    }
    public void setStatus(int status){
        this.status=status;
        Log.e("Tag","setStatus"+status);
        new Handler(Looper.myLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                invalidate();
            }
        },100);
    }
    private void myDraw(){

    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
//    }

//    @Override
//    protected void onDraw(Canvas canvas) {
//        super.onDraw(canvas);
//        Log.e("Tag","onDraw"+status);
        centre = getWidth() / 2; //获取圆心的x坐标
        radius = (int) (centre - roundWidth / 2); //圆环的半径

        /**
         * 画最外层的背景
         */
        paint.setColor(roundBackColor); //设置圆的颜色
        paint.setStyle(Paint.Style.FILL); //设置实心
        paint.setAntiAlias(true);  //消除锯齿
        canvas.drawCircle(centre, centre, radius, paint); //画出圆
        /**
         * 画最外层的大圆环
         */
        paint.setColor(roundColor); //设置圆环的颜色
        paint.setStyle(Paint.Style.STROKE); //设置空心
        paint.setStrokeWidth(lineWidth); //设置圆环的宽度
        paint.setAntiAlias(true);  //消除锯齿
        canvas.drawCircle(centre, centre, radius, paint); //画出圆环

        if (!isCheckPause){
            //画进度百分比
            paint.setStrokeWidth(0);
            paint.setColor(textColor);
            paint.setTextSize(textSize);
            paint.setTypeface(Typeface.DEFAULT); //设置字体
            int percent = (int) (((float) progress / (float) max) * 100);  //中间的进度百分比，先转换成float在进行除法运算，不然都为0
            float textWidth = paint.measureText(percent + "");   //测量字体宽度，我们需要根据字体的宽度设置在圆环中间

            if (textIsDisplayable && style == STROKE) {
//            canvas.drawText(percent + "%", centre - textWidth / 2, centre + textSize/2, paint); //画出进度百分比
                canvas.drawText(percent + "", centre - textWidth / 2, centre + textSize / 2 - 5, paint); //画出进度百分比
                paint.setTextSize(textSize * 2 / 3);
                canvas.drawText("%", centre + textWidth / 2, centre + textSize / 2 - 4, paint);
            }
        }else {
            //下载or暂停下载
            paint.setStrokeWidth(4);
            switch (status){
                case STATUS.START:
                    //画下箭头
                    int rectX=centre/2;
                    int rectY=centre/2;
                    paint.setStrokeWidth(lineWidth);
                    paint.setStyle(Paint.Style.STROKE);
                    Path linePath=new Path();
                    linePath.moveTo(centre-rectX, centre);
                    linePath.lineTo(centre, centre+rectY);
                    linePath.lineTo(centre+rectX, centre);
                    linePath.moveTo(centre, centre-rectY);
                    linePath.lineTo(centre, centre+rectY);
                    canvas.drawPath(linePath, paint);
                    break;
                case STATUS.DOWN:
                    int rectWidth=centre/3;
                    paint.setStyle(Paint.Style.FILL);
                    canvas.drawRect(centre-rectWidth,centre-rectWidth,centre+rectWidth,centre+rectWidth,paint);
                    break;
                case STATUS.PAUSE:
                    int rectX1=centre/4;
                    int rectY1=centre/3;
                    paint.setStyle(Paint.Style.FILL);
                    canvas.drawLine(centre-rectX1,centre-rectY1,centre-rectX1,centre+rectY1,paint);
                    canvas.drawLine(centre+rectX1,centre-rectY1,centre+rectX1,centre+rectY1,paint);
                    break;
            }
        }

        /**
         * 画圆弧 ，画圆环的进度
         */
//        oval = new RectF(centre - radius + lineWidth, centre - radius + lineWidth, centre + radius - lineWidth, centre + radius - lineWidth);  //用于定义的圆弧的形状和大小的界限
        Log.e("Tag",(centre - radius + lineWidth)+"---"+(centre - radius + lineWidth)+"---"+(centre + radius - lineWidth)+
        "---"+(centre + radius - lineWidth));
        //设置进度是实心还是空心
        paint.setStrokeWidth(roundWidth); //设置圆环的宽度
        paint.setColor(roundProgressColor);  //设置进度的颜色

        if (max!=0){
            switch (style) {
                case STROKE: {
                    paint.setStyle(Paint.Style.STROKE);
//                    Log.e("Tag","progress="+progress+"-max="+max);
                    canvas.drawArc(oval, -90, 360 * progress / max, false, paint);
                    break;
                }
                case FILL: {
//                    paint.setStyle(Paint.Style.FILL_AND_STROKE);
                    if (progress != 0)
                        canvas.drawArc(oval, 270, 360 * progress / max, true, paint);
                    break;
                }
            }
        }
    }


    public synchronized long getMax() {
        return max;
    }

    /**
     * 设置进度的最大值
     *
     * @param max
     */
    public synchronized void setMax(long max) {
        if (max < 0) {
            throw new IllegalArgumentException("max not less than 0");
        }
        this.max = max;
    }

    /**
     * 获取进度.需要同步
     *
     * @return
     */
    public synchronized long getProgress() {
        return progress;
    }
    /**
     * 防止双击事件的发生
     **/
    private static long clickTime;
    private static long lastClickTime;

    public static boolean checkDoubleClick() {
        clickTime = SystemClock.elapsedRealtime();
        if ((clickTime > lastClickTime) && ((clickTime - lastClickTime) > 400)) {
            lastClickTime = clickTime;
            return false;
        }
        return true;
    }
    /**
     * 设置进度，此为线程安全控件，由于考虑多线的问题，需要同步
     * 刷新界面调用postInvalidate()能在非UI线程刷新
     *
     * @param progress
     */
    public synchronized void setProgress(long progress) {
        if (progress < 0) {
            throw new IllegalArgumentException("progress not less than 0");
        }
//        if (progress > max) {
//            progress = max;
//        }
        if (progress <= max) {
//            Log.e("Tag","提示:progress"+progress);
            this.progress = progress;
//            ((ViewGroup)getParent()).postInvalidate();
            postInvalidate();
//            if (checkDoubleClick())
//                invalidate();

//            forceLayout();
//            requestLayout();
        }

    }


    public int getCricleColor() {
        return roundColor;
    }

    public void setCricleColor(int cricleColor) {
        this.roundColor = cricleColor;
    }

    public int getCricleProgressColor() {
        return roundProgressColor;
    }

    public void setCricleProgressColor(int cricleProgressColor) {
        this.roundProgressColor = cricleProgressColor;
    }

    public int getTextColor() {
        return textColor;
    }

    public void setTextColor(int textColor) {
        this.textColor = textColor;
    }

    public float getTextSize() {
        return textSize;
    }

    public void setTextSize(float textSize) {
        this.textSize = textSize;
    }

    public float getRoundWidth() {
        return roundWidth;
    }

    public void setRoundWidth(float roundWidth) {
        this.roundWidth = roundWidth;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureLong(widthMeasureSpec), measureShort(heightMeasureSpec));
    }

    private int measureLong(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if ((specMode == MeasureSpec.EXACTLY)) {
            result = specSize;
        } else {
            result = getPaddingLeft() + getPaddingRight() + 100;
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    private int measureShort(int measureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = (int)textSize + getPaddingTop() + getPaddingBottom();
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }
}
